package com.hyst.web;

import com.hyst.common.ResultBean;
import com.hyst.common.ResultPage;
import com.hyst.domain.FreeAudition;
import com.hyst.service.FreeAuditionService;
import com.hyst.utils.POIUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @Description:学生表controller
 * @author：cb
 *@Date：2018年10月09日
 */
@RestController
@RequestMapping("freeAuditions")
@CrossOrigin(maxAge = 3600, origins = "*")
public class FreeAuditionController {

    @Autowired
    private FreeAuditionService freeAuditionService;

    @GetMapping
    public ResultPage<FreeAudition> list(FreeAudition freeAudition) {
        return ResultPage.success(freeAuditionService.list(freeAudition));
    }

    @PostMapping
    public ResultBean<FreeAudition> creat(final FreeAudition freeAudition) {
        if (freeAudition.getApplyTime() == null) {
            freeAudition.setApplyTime(new Date());
        }
        if(StringUtils.isNotBlank(freeAudition.getRecommendId()) && "请选择".equals(freeAudition.getRecommendId().trim())){
            freeAudition.setRecommendId(null);
            freeAudition.setRecommendName(null);
        }
        return ResultBean.success(freeAuditionService.insert(freeAudition));
    }

    /**
     * @return ResultBean<FreeAudition>
     */
    @GetMapping("{orderId}")
    public ResultBean<FreeAudition> getByPriKey(@PathVariable("orderId") final String orderId) {
        return ResultBean.success(freeAuditionService.getByPriKey(orderId));
    }

    /**
     * @return ResultBean<FreeAudition>
     */
    @PatchMapping("{orderId}")
    public ResultBean<FreeAudition> update(final FreeAudition freeAudition) {
        return ResultBean.success(freeAuditionService.update(freeAudition));
    }

    /**
     * @return ResultBean<FreeAudition>
     */
    //@PutMapping("{orderId}")
    @PostMapping("{orderId}")
    public ResultBean<FreeAudition> updatePatch(@PathVariable("orderId") final String orderId,
                                                final FreeAudition freeAudition) {
        return ResultBean.success(freeAuditionService.updateSelective(freeAudition));
    }

    /**
     * @return ResultBean<FreeAudition>
     */
    @DeleteMapping("{orderId}")
    public ResultBean<FreeAudition> delete(@PathVariable("orderId") final String orderId) {
        return ResultBean.success(freeAuditionService.delete(orderId));
    }

    // 2018-10-13 chenbin: 新增，提交信息至试听管理与学员中心
    @GetMapping("InsertToAudition/{orderId}")
    public ResultBean<FreeAudition> InsertToAudition(@PathVariable("orderId") final String orderId) {
        System.out.println(orderId);
        return ResultBean.success(freeAuditionService.InsertToAudition(orderId));
    }

    // 2018-10-13 chenbin: 新增，提交信息至试听管理与学员中心
    @GetMapping("UpdateAudition/{orderId}")
    public ResultBean<FreeAudition> UpdateAudition(@PathVariable("orderId") final String orderId) {
        System.out.println(orderId);
        return ResultBean.success(freeAuditionService.UpdateAudition(orderId));
    }

// 2018-10-9 chenbin: 新增

    @GetMapping("saveAllot/{postMsg}")
    public ResultBean<FreeAudition> saveAllot(@PathVariable("postMsg") final String postMsg) {
        System.out.println(postMsg);
        return ResultBean.success(freeAuditionService.saveAllot(postMsg));
    }

    @PostMapping("saveRemark")
    public ResultBean<FreeAudition> saveRemark(@RequestParam(value = "postMsg") String postMsg) {
        System.out.println(postMsg);
        return ResultBean.success(freeAuditionService.saveRemark(postMsg));
    }

    @PostMapping("saveState")
    public ResultBean<FreeAudition> saveState(@RequestParam(value = "postMsg") String postMsg) {
        System.out.println("2018-9-25 chenbin:" + postMsg);
        return ResultBean.success(freeAuditionService.saveState(postMsg));
    }

    @GetMapping("saveDelete/{orderId}")
    public ResultBean<FreeAudition> saveDelete(@PathVariable("orderId") final String orderId) {
        System.out.println(orderId);
        return ResultBean.success(freeAuditionService.saveDelete(orderId));
    }

    // 2018-10-13 chenbin: 下拉框条件查询
    @GetMapping("selectByCondition/{selectCondition}")
    public ResultPage<FreeAudition> selectByCondition(final FreeAudition freeAudition, @PathVariable("selectCondition") final String selectCondition) {
        String condition = null;
//		try {
//			condition =new String(selectCondition.getBytes("ISO-8859-1"), "utf8");//解决中文格式乱码
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}'
//		System.out.println(condition);
        return ResultPage.success(freeAuditionService.selectByCondition(freeAudition, selectCondition));
    }

    // 2018-10-13 chenbin: 搜索框条件搜索
    @GetMapping("searchByPhone/{phone}")
    public ResultPage<FreeAudition> searchByPhone(final FreeAudition freeAudition, @PathVariable("phone") final String phone) {
//		String condition = null;
//		try {
//			condition =new String(phone.getBytes("ISO-8859-1"), "utf8");//解决中文格式乱码
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		System.out.println(condition);
        return ResultPage.success(freeAuditionService.searchByPhone(freeAudition, phone));
    }

    // 2018-10-13 chenbin: 搜索框条件搜索
    @GetMapping("searchByName/{name}")
    public ResultPage<FreeAudition> searchByName(final FreeAudition freeAudition, @PathVariable("name") final String name) {
        String condition = null;
        try {
            condition = new String(name.getBytes("ISO-8859-1"), "utf8");//解决中文格式乱码
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(condition);
        return ResultPage.success(freeAuditionService.searchByName(freeAudition, condition));
    }

    // 2018-9-25 chenbin: 新增，获取顾问UniqueId
    @GetMapping("getUID")
    public static String getUIDFromSession() {
        String uniqueId = "uniqueId";

        return uniqueId;
    }

    /**
     * 下载记录
     */
    @GetMapping("download/{orderId}")
    public void downloan(@PathVariable("orderId") final String orderId,
                                             HttpServletResponse response) throws Exception{
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        FreeAudition freeAudition=freeAuditionService.getByPriKey(orderId);
            try {
                XWPFDocument doc=POIUtil.genFreeDocument(freeAudition);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                doc.write(baos);

                response.setContentType("application/octet-stream");
                String fileName = freeAudition.getEnName();
                if (getRequest().getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {   //IE浏览器
                    fileName = URLEncoder.encode(fileName + ".docx", "UTF-8");
                } else {
                    fileName = URLDecoder.decode(fileName + ".docx");//其他浏览器
                }

                response.setHeader("Content-disposition", "attachment; filename="
                        + new String(fileName.getBytes("utf-8"), "ISO8859-1")); // 指定下载的文件名
                os.write(baos.toByteArray());
                os.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (os != null) {
                    os.close();
                }
            }
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attrs.getRequest();
    }
}
